package top.codingfly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.util.Assert;
import top.codingfly.mapper.entity.AreaCodeEntity;
import top.codingfly.mapper.AreaCodeMapper;
import top.codingfly.service.IAreaCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 行政区划表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-18
 */
@Service
public class AreaCodeServiceImpl extends ServiceImpl<AreaCodeMapper, AreaCodeEntity> implements IAreaCodeService {

    @Resource
    public AreaCodeMapper areaCodeMapper;

    @Override
    public void up(String code) {
        AreaCodeEntity entity = areaCodeMapper.selectOne(new LambdaQueryWrapper<AreaCodeEntity>().eq(AreaCodeEntity::getCode, code).last(" LIMIT 1"));
        Assert.isTrue(entity!=null, "code:"+code+"不存在");
        AreaCodeEntity sortUpOne = areaCodeMapper.sortUpOne(entity.getParentCode(), entity.getSort());
        if (sortUpOne==null) {
            return;
        }
        Integer bigSort = entity.getSort();
        entity.setSort(sortUpOne.getSort());
        entity.setUpdateTime(new Date());
        sortUpOne.setSort(bigSort);
        sortUpOne.setUpdateTime(new Date());
        areaCodeMapper.updateById(sortUpOne);
        areaCodeMapper.updateById(entity);
    }

    @Override
    public void down(String code) {
        AreaCodeEntity entity = areaCodeMapper.selectOne(new LambdaQueryWrapper<AreaCodeEntity>().eq(AreaCodeEntity::getCode, code).last(" LIMIT 1"));
        Assert.isTrue(entity!=null, "code:"+code+"不存在");
        AreaCodeEntity sortDownOne = areaCodeMapper.sortDownOne(entity.getParentCode(), entity.getSort());
        if (sortDownOne==null) {
            return;
        }
        Integer smallSort = entity.getSort();
        entity.setSort(sortDownOne.getSort());
        entity.setUpdateTime(new Date());
        sortDownOne.setSort(smallSort);
        sortDownOne.setUpdateTime(new Date());
        areaCodeMapper.updateById(sortDownOne);
        areaCodeMapper.updateById(entity);
    }

}
